<template>
  <div class="page-content">
    <div class="script-config">
      <div class="page-header">
        <div class="header-actions">
          <div 
            class="custom-upload-btn"
            @click="showAddConfigDialog"
          >
            <i class="el-icon-plus"></i>
            <span>新增配置</span>
          </div>
        </div>
      </div>

      <!-- 配置列表 -->
      <div class="config-list-container">
        <div v-if="configLoading" class="loading-container">
          <div class="loading-spinner">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>
        </div>
        <div v-else class="table-container">
          <div class="table-header">
            <div class="header-cell name-col">配置名称</div>
            <div class="header-cell game-col">游戏</div>
            <div class="header-cell description-col">描述</div>
            <div class="header-cell time-col">创建时间</div>
            <div class="header-cell actions-col">操作</div>
          </div>
          <div class="table-body">
            <div v-if="configList.length === 0" class="empty-state">
              <div class="empty-icon">📋</div>
              <div class="empty-text">暂无配置数据</div>
              <div class="empty-desc">点击右上角"新增配置"按钮添加配置</div>
            </div>
            <div v-else v-for="config in configList" :key="config.id" class="table-row">
              <div class="cell name-col">{{ config.name }}</div>
              <div class="cell game-col">{{ config.game }}</div>
              <div class="cell description-col">{{ config.description || '-' }}</div>
              <div class="cell time-col">{{ formatDate(config.create_time) }}</div>
              <div class="cell actions-col">
                <div class="config-actions">
                  <button class="action-btn edit" @click="editConfig(config)">
                    编辑
                  </button>
                  <button class="action-btn delete" @click="deleteConfigConfirm(config)">
                    删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 配置对话框 -->
      <el-dialog 
        :title="editingConfig ? '编辑配置' : '新增配置'"
        v-model="showConfigDialog" 
        width="800px"
        :close-on-click-modal="false"
      >
        <el-form 
          ref="configFormRef"
          :model="configForm" 
          :rules="configRules"
          label-width="120px"
        >
          <el-form-item label="配置名称" prop="name">
            <el-input v-model="configForm.name" placeholder="请输入配置名称" />
          </el-form-item>
          <el-form-item label="游戏" prop="game">
            <el-select v-model="configForm.game" placeholder="请选择游戏" style="width: 100%">
              <el-option 
                v-for="game in supportedGames" 
                :key="game" 
                :label="game" 
                :value="game"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input 
              v-model="configForm.description" 
              type="textarea" 
              :rows="3"
              placeholder="请输入配置描述（可选）"
            />
          </el-form-item>

          <!-- 配置内容 -->
          <div v-if="configTemplate.length > 0" class="config-content">
            <h3>配置详情</h3>
            <div v-for="item in configTemplate" :key="item.key" class="config-item">
              <el-form-item :label="item.label" :prop="`content.${item.key}`">
                <el-select 
                  v-if="item.type === 'select'"
                  v-model="configForm.content[item.key]"
                  :placeholder="`请选择${item.label}`"
                  style="width: 100%"
                >
                  <el-option 
                    v-for="option in item.options" 
                    :key="option.value" 
                    :label="option.label" 
                    :value="option.value"
                  />
                </el-select>
                <el-input 
                  v-else-if="item.type === 'input'"
                  v-model="configForm.content[item.key]"
                  :placeholder="`请输入${item.label}`"
                />
                <el-input-number 
                  v-else-if="item.type === 'number'"
                  v-model="configForm.content[item.key]"
                  :min="item.min || 0"
                  :max="item.max || 999"
                  style="width: 100%"
                />
                <el-switch 
                  v-else-if="item.type === 'switch'"
                  v-model="configForm.content[item.key]"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
        
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleConfigDialogClose">取消</el-button>
            <el-button type="primary" @click="saveConfig" :loading="configSaving">
              {{ editingConfig ? '更新' : '创建' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getUserConfigs, 
  createConfig, 
  getConfig, 
  updateConfig, 
  deleteConfig, 
  getGameConfigTemplate
} from '../api/configs'

export default {
  name: 'ScriptConfig',
  setup() {
    const configLoading = ref(false)
    const configList = ref([])
    const supportedGames = ref([])
    
    // 配置对话框
    const showConfigDialog = ref(false)
    const configFormRef = ref()
    const editingConfig = ref(null)
    const configSaving = ref(false)
    const configTemplate = ref([])
    
    // 配置表单
    const configForm = ref({
      name: '',
      game: '尤弥尔传奇国际服',
      description: '',
      content: {}
    })
    
    const configRules = ref({
      name: [
        { required: true, message: '请输入配置名称', trigger: 'blur' },
        { min: 2, max: 50, message: '配置名称长度在2到50个字符', trigger: 'blur' }
      ],
      game: [
        { required: true, message: '请选择游戏', trigger: 'change' }
      ],
      'content.daily_hang_map': [
        { required: true, message: '请选择日常挂机地图', trigger: 'change' }
      ]
    })

    // 加载配置数据
    const loadConfigs = async () => {
      configLoading.value = true
      try {
        const configsResponse = await getUserConfigs()
        configList.value = configsResponse.data || []
      } catch (error) {
        console.error('加载配置失败:', error)
        const errorMessage = error.response?.data?.error || 
                          error.response?.data?.message || 
                          error.message || 
                          '未知错误'
        ElMessage.error('加载配置失败: ' + errorMessage)
      } finally {
        configLoading.value = false
      }
    }

    // 显示添加配置对话框
    const showAddConfigDialog = async () => {
      editingConfig.value = null
      resetConfigForm()
      showConfigDialog.value = true
      // 确保加载默认游戏模板
      await loadGameTemplate('尤弥尔传奇国际服')
    }

    // 编辑配置
    const editConfig = async (config) => {
      editingConfig.value = config
      
      try {
        const response = await getConfig(config.id)
        const configData = response.data
        
        configForm.value = {
          name: configData.name,
          game: configData.game,
          description: configData.description || '',
          content: configData.content || {}
        }
        
        await loadGameTemplate(configData.game)
        showConfigDialog.value = true
      } catch (error) {
        console.error('获取配置详情失败:', error)
        const errorMessage = error.response?.data?.error || 
                          error.response?.data?.message || 
                          error.message || 
                          '未知错误'
        ElMessage.error('获取配置详情失败: ' + errorMessage)
      }
    }

    // 重置配置表单
    const resetConfigForm = () => {
      configForm.value = {
        name: '',
        game: '尤弥尔传奇国际服',
        description: '',
        content: {}
      }
      configTemplate.value = []
    }

    // 加载游戏配置模板
    const loadGameTemplate = async (game) => {
      try {
        const response = await getGameConfigTemplate(game)
        configTemplate.value = response.data || []
        
        // 初始化配置内容的默认值
        configTemplate.value.forEach(item => {
          if (configForm.value.content[item.key] === undefined) {
            configForm.value.content[item.key] = item.default || ''
          }
        })
      } catch (error) {
        console.error('加载游戏模板失败:', error)
        const errorMessage = error.response?.data?.error || 
                          error.response?.data?.message || 
                          error.message || 
                          '未知错误'
        ElMessage.error('加载游戏模板失败: ' + errorMessage)
      }
    }

    // 保存配置
    const saveConfig = async () => {
      try {
        await configFormRef.value.validate()
        
        configSaving.value = true
        const configData = {
          name: configForm.value.name,
          game: configForm.value.game,
          description: configForm.value.description,
          content: configForm.value.content
        }
        
        if (editingConfig.value) {
          await updateConfig(editingConfig.value.id, configData)
          ElMessage.success('配置更新成功')
        } else {
          await createConfig(configData)
          ElMessage.success('配置创建成功')
        }
        
        showConfigDialog.value = false
        resetConfigForm()
        loadConfigs() // 重新加载配置列表
      } catch (error) {
        console.error('保存配置失败:', error)
        const errorMessage = error.response?.data?.error || 
                          error.response?.data?.message || 
                          error.message || 
                          '未知错误'
        ElMessage.error('保存配置失败: ' + errorMessage)
      } finally {
        configSaving.value = false
      }
    }

    // 删除配置确认
    const deleteConfigConfirm = async (config) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除配置"${config.name}"吗？删除后无法恢复。`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await deleteConfig(config.id)
        ElMessage.success('配置删除成功')
        loadConfigs() // 重新加载配置列表
      } catch (error) {
        if (error === 'cancel') return
        console.error('删除配置失败:', error)
        const errorMessage = error.response?.data?.error || 
                          error.response?.data?.message || 
                          error.message || 
                          '未知错误'
        ElMessage.error('删除配置失败: ' + errorMessage)
      }
    }

    // 处理配置对话框关闭
    const handleConfigDialogClose = () => {
      showConfigDialog.value = false
      resetConfigForm()
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      try {
        const date = new Date(dateString)
        if (isNaN(date.getTime())) return '-'
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
      } catch (error) {
        console.error('日期格式化失败:', error)
        return '-'
      }
    }

    onMounted(async () => {
      // 直接在前端定义支持的游戏列表
      supportedGames.value = ['尤弥尔传奇国际服']
      await loadConfigs()
    })

    return {
      configLoading,
      configList,
      supportedGames,
      showConfigDialog,
      configFormRef,
      editingConfig,
      configSaving,
      configTemplate,
      configForm,
      configRules,
      loadConfigs,
      showAddConfigDialog,
      editConfig,
      resetConfigForm,
      loadGameTemplate,
      saveConfig,
      deleteConfigConfirm,
      handleConfigDialogClose,
      formatDate
    }
  }
}
</script>

<style scoped>
.page-content {
  padding: 0;
  height: 100%;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.script-config {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 32px;
  padding: 0 4px;
}

/* 自定义主要操作按钮样式 */
.custom-upload-btn {
  background: #409EFF;
  color: white;
  border: none;
  border-radius: 6px;
  width: 120px;
  height: 40px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 500;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.custom-upload-btn:hover {
  background: #66b1ff;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
}

.custom-upload-btn:active {
  background: #3a8ee6;
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
}

.custom-upload-btn i {
  font-size: 14px;
  margin-right: 6px;
}

.custom-upload-btn span {
  font-size: 14px;
}

/* 配置列表容器 */
.config-list-container {
  flex: 1;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.05);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.loading-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid rgba(0, 0, 0, 0.1);
  border-top: 3px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-spinner p {
  margin: 0;
  color: #86868b;
  font-size: 16px;
}

/* 表格样式 */
.table-container {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: grid;
  grid-template-columns: 200px 150px 1fr 180px 200px;
  background: #f8f9fa;
  padding: 16px 20px;
  font-weight: 600;
  color: #1d1d1f;
  font-size: 14px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  gap: 16px;
}

.table-body {
  flex: 1;
  overflow: auto;
}

.table-row {
  display: grid;
  grid-template-columns: 200px 150px 1fr 180px 200px;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  align-items: center;
  transition: all 0.2s ease;
  gap: 16px;
}

.table-row:hover {
  background: rgba(0, 0, 0, 0.02);
}

.header-cell, .cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.cell {
  color: #1d1d1f;
}

.config-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.action-btn {
  background: none;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  padding: 6px 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  font-weight: 500;
}

.action-btn.edit {
  color: #007aff;
  border-color: rgba(0, 122, 255, 0.2);
}

.action-btn.edit:hover {
  background: rgba(0, 122, 255, 0.1);
}

.action-btn.delete {
  color: #ff3b30;
  border-color: rgba(255, 59, 48, 0.2);
}

.action-btn.delete:hover:not(:disabled) {
  background: rgba(255, 59, 48, 0.1);
}

.action-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 20px;
  color: #86868b;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 16px;
  font-weight: 500;
  color: #1d1d1f;
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: #86868b;
}

.config-content {
  margin-top: 20px;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #f9fafb;
}

.config-content h3 {
  margin: 0 0 16px 0;
  color: #1f2937;
  font-size: 16px;
  font-weight: 600;
}

.config-item {
  margin-bottom: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>